<!--地址管理-->
<template>
  <view>
    <customHeader
      v-if="isShowCustomNavBar"
      :navbarData.sync="navbarData"
      @hasGetAddress="hasGetAddress"
      @currentPage="getCurrentPage"
      @setDeafaultAddress="setDeafaultAddress"
    ></customHeader>
    <scroll-view
      :style="{ height: windowHeight + 'px', background: '#fff' }"
      :scroll-y="flag"
    >
      <view :class="currentPage === 0 ? '' : 'hidden'">
        <addressList
          :type="type"
          :addressListArray="addressListArray"
          :checkIndex="checkIndex"
          ref="addressList"
          @currentPage="getCurrentPage"
          @moveAddressItem="handelMoveItem"
          @setDeafaultAddress="setDeafaultAddress"
          @reSetAddModel="reSetAddModel"
          @changShowGetAddress="changShowGetAddress"
          :skuIdArr="skuIdArr"
          @reSetAddressId="reSetAddressId"
        ></addressList>
      </view>
      <view :class="currentPage === 1 ? '' : 'hidden'">
        <addressAdd
          @currentPage="getCurrentPage"
          @reSetAddModel="reSetAddModel"
          :isIos="isIos"
          ref="addressAdd"
          @setDeafaultAddress="setDeafaultAddress"
          :openType="type"
          :showgetAddress="showgetAddress"
          :skuIdArr="skuIdArr"
          :showAddList="showAddList"
          :navFlag="navbarData.flag"
          @reSetAddressId="reSetAddressId"
        >
        </addressAdd>
      </view>
      <view :class="currentPage === 2 ? '' : 'hidden'">
        <addressEdit
          :isIos="isIos"
          @currentPage="getCurrentPage"
          ref="addressEdit"
          :fromPage="fromPage"
          @setDeafaultAddress="setDeafaultAddress"
          @hasGetAddress="hasGetAddress"
          :hasGetAddressData.sync="hasGetAddressData"
          :navFlag="navbarData.flag"
        ></addressEdit>
      </view>
      <view :class="currentPage === 3 ? '' : 'hidden'">
        <addressDefault
          @currentPage="getCurrentPage"
          @applyGift="applyGift"
          ref="addressDefault"
          :defaultAddress.sync="defaultAddress"
          @setFromPage="setFromPage"
        ></addressDefault>
      </view>
    </scroll-view>
    <!-- -->
    <view
      class="mask-box-2"
      v-if="isTip"
      @click.stop="isTip = false"
      @touchmove.stop.prevent
      catchtouchmove="true"
    >
      <view
        class="params-padding-box-3"
        :style="{ bottom: isIpx ? '558rpx' : '414rpx' }"
        @click.stop="stopClick"
      >
        <image
          style="width: 654rpx; height: auto"
          mode="widthFix"
          :src="tipBgImg"
          alt=""
        />

        <view
          style="
            position: absolute;
            bottom: 102rpx;
            height: 80rpx;
            box-sizing: border-box;
            padding: 0 64rpx;
            width: 100%;
            display: flex;
            flex-direction: row;
            justify-content: space-around;
            align-items: center;
          "
        >
          <view
            @click.stop="isTip = false"
            style="width: 255rpx; height: 80rpx"
          ></view>
          <view
            v-if="isTip == 'tip'"
            @click.stop="reSetAddModelPass"
            style="width: 255rpx; height: 80rpx"
          ></view>
          <button
            v-else
            open-type="contact"
            show-message-card="true"
            @bindcontact="reSetAddModelCancel"
            style="width: 255rpx; height: 80rpx; background-color: transparent"
          ></button>
        </view>
        <view
          @click.stop="isTip = false"
          style="
            position: absolute;
            top: 15rpx;
            right: 14rpx;
            width: 90rpx;
            height: 90rpx;
          "
        ></view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
import AddressList from "@/pages/customer/components/addressList.vue";
import AddressAdd from "@/pages/customer/components/addressAdd.vue";
import AddressEdit from "@/pages/customer/components/addressEdit.vue";
import AddressDefault from "@/pages/customer/components/addressDefault.vue";
import customHeader from "@/components/common/custom";
import api from "@/api/api";
import {
  SYSTEM_INFO,
  MERCHANT_INFO,
  USER_INFO,
  USER_SPECICAL_INFO,
  CUSTOMER_INFO,
  CART_KEY,
} from "@/utils/constant";
export default {
  config: {
    navigationBarTitleText: "地址管理",
  },
  data() {
    return {
      flag: true,
      windowHeight: 0,
      nowPages: "",
      isShowCustomNavBar: true,
      navbarData: {
        flag: 1, //
        name: "地址管理", //导航栏 中间的标题
      },
      addressListArray: [],
      receiverInfo: {},
      //显示当前组件 0 列表 1新增 2编辑
      currentPage: 0,
      checkIndex: -1,
      type: "", //哪个页面跳转过来的
      skuId: "",
      skuIdArr: [],
      activitySelectionId: "",
      params: {},
      fromSuccess: false,
      // eve: 'formal', // trial 测试版  formal正式版
      eve: api.environment,
      defaultAddress: {},
      showgetAddress: false,
      showAddList: false,
      giftInfo: null,
      giftInfoOpt: {},
      secondRequest: false,
      streetAddressId: "",
      fromPage: "",
      hasGetAddressData: false,
      isIos: false,
      orderNo: null,
      cb: null,
      tipBgImg: "",
      isTip: null,
      isIpx: false,
	  no:null
    };
  },
  components: {
    addressList: AddressList,
    addressAdd: AddressAdd,
    addressEdit: AddressEdit,
    customHeader: customHeader,
    addressDefault: AddressDefault,
  },
  async onLoad(option) {
    this.isIpx =
      wx.getSystemInfoSync().system.includes("iOS") &&
      wx.getSystemInfoSync()?.safeArea?.top > 20; //isIpx;
    let that = this;
    const systemInfoSync = uni.getSystemInfoSync();
    this.windowHeight =
      systemInfoSync.windowHeight - getApp().globalData.navBarHeight;
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    this.currentPage = 0;
    this.type = option.type === undefined ? "" : option.type;
    this.orderNo = option.orderNo || null;
	 this.no = option.no || null;
    //  是否抽签购进入
    if (option.type == "draw") {
      let params = JSON.parse(decodeURIComponent(option.options));
      this.skuId = params.skuId;
      this.skuIdArr[0] = params.skuId;
      this.activitySelectionId = params.activitySelectionId;
      this.params = params;
      if (params.disableShare) {
        uni.hideShareMenu();
      }
      this.isSecondResultRquest();
    }
    // 标记通过订单页立即完善按钮过来的
    if (option.fromPage == "order" && option.addressId) {
      this.fromPage = option.fromPage;
      this.currentPage = 2;
      this.receiverInf(option.addressId, "edit");
    }
    if (option.type == "gift" && option.id) {
      this.giftInfoOpt = option;
      await this.getGiftInfoById(option.id);
      this.navbarData.name = "确认收货地址";
    }

    this.$refs.addressList.setOrgType(this.type);
    this.$refs.addressAdd.setOrgType(this.type);
    this.$refs.addressEdit.setOrgType(this.type);
    this.getUserAddress(-1);
    this.$commonSensors.addressManagement();
    this.isIos =
      wx.getSystemInfoSync().system.includes("iOS") &&
      wx.getSystemInfoSync()?.safeArea?.top > 20;
    setTimeout(() => {
      that.$commonSensors.setProfileAddress(that.addressListArray);
    }, 1500);
  },
  onShow() {
    if (this.fromSuccess) {
      uni.navigateBack({
        delta: -1,
      });
    }
    let that = this;
    getApp().cl_tracker.track("mini_program_view", {
      path: this.nowPages,
      pageName: "地址管理",
    });
  },
  methods: {
		/**
		 * 展示弱提示
		 * @param {Object} msg 文案
		 */
		handleShowTextToast(msg){
			try{
				this.$refs.toastPopup.showToast(msg);
			}catch(e){}
		},
		/**
		 * 若提示按钮点击回调
		 * @param {Object} data.type 类型：confirm确定，cancel取消
		 * @param {Object} data.callBackData 呼气弹窗时传入的数据
		 */
		onToastPopupClick(data){},
		stopClick() {
		  return false
		},
    //  礼遇信息查询
    async getGiftInfoById(id) {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const res = await api.getGiftStatus(
        {
          header: {
            jwt: customerInfo.jwt,
          },
        },
        id
      );
      if (res.data && res.code === 1000) {
        this.giftInfo = res.data;
      }
    },
    // 标记是通过会员礼遇点击立即完善按钮过来的
    setFromPage(val) {
      this.fromPage = val;
    },
    //用户收货地址
    getUserAddress: async function (id, flag) {
      this.showAddList = !!flag;
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      // let customerId = customerInfo.customerId;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      const json = await api.getUserAddress({
        header: {
          jwt: jwt,
        },
      });
      if (json.code === 1000) {
        let storageId = uni.getStorageSync("addressId");
        if (id !== -1 && json.data.content.length > 0 && this.type == "order") {
          this.$refs.addressList.chooseAddress(id);
        }
        this.addressListArray = json.data.content;
        if (
          this.addressListArray.length == 0 &&
          (this.type == "order" || this.type == "draw" || this.type == "gift")
        ) {
          this.currentPage = 1;
        }
        let hasDefault = this.addressListArray.filter((item) => {
          return item.isDefault == 1;
        });
        // if (this.type == 'gift' && !flag) {
        //   if (this.addressListArray.length > 0 && hasDefault.length > 0) {
        //     this.currentPage = 3;
        //     this.defaultAddress = hasDefault[0]
        //   } else if (this.addressListArray.length > 0 && hasDefault.length == 0) {
        //     this.currentPage = 1
        //     this.showgetAddress = true
        //   }
        // }
        this.$refs.addressList.refreshList(this.addressList);
      } else {
        this.handleShowTextToast(json.msg);
      }
      that.showLoading = false;
    },

    /**
     * 获取用户单个地址
     * @param id
     * @returns {Promise<void>}
     */
    receiverInf: async function (id, type) {
      let that = this;
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      let customerId = customerInfo.customerId;
      let jwt = customerInfo.jwt;
      const json = await api.getAddressInfoById(
        {
          header: {
            jwt: jwt,
          },
        },
        customerId,
        id
      );
      if (json.code === 1000) {
        this.receiverInfo = json.data;
        this.$refs.addressEdit.refresh(this.receiverInfo);
        if (type == "edit") {
          this.$refs.addressEdit.openAddressPickerNew(3);
        }
      } else {
        this.handleShowTextToast(json.msg);
      }
      that.showLoading = false;
    },
    hasGetAddress(showFlag) {
      this.hasGetAddressData = !!showFlag;
    },
    //切换页面组件获取用户单个地址
    getCurrentPage(cur, id, flag) {
      this.currentPage = cur;
      if (cur !== 1 && cur !== 0) {
        this.receiverInf(id);
      }
      // 刷新地址信息
      if (cur === 0) {
        this.getUserAddress(id, true);
        this.navbarData.flag = 1;
        // 在会员礼默认地址页面点击选择地址跳地址列表页，加navbarData.flag3能返回默认页
        if (this.fromPage == "gift") {
          this.receiverInf(id, "edit");
          this.navbarData.flag = 3;
        }
      }
      if (cur == 1 || cur == 2) {
        this.navbarData.flag = 2;
        // 在会员礼默认地址页点击立即完善按钮到编辑页，加flag3能返回默认页， flag true是列表点击编辑
        if (cur == 2 && this.fromPage == "gift" && !flag) {
          this.receiverInf(id, "edit");
          this.navbarData.flag = 3;
        }
        if (flag == "drawStreet") {
          this.receiverInf(id, "edit");
        }
      }
      this.navbarData.name = "地址管理";
    },
    setDeafaultAddress({ info, type }) {
      this.navbarData.flag = 1;
      this.defaultAddress = info || this.defaultAddress;
      // this.currentPage = 3
      this.currentPage = 0;
      this.navbarData.name = "确认收货地址";
      this.getUserAddress(-1);
      if (type == "list" && this.type == "gift") {
        this.applyGift(this.defaultAddress);
      }
    },
    changShowGetAddress(flag) {
      this.showgetAddress = flag;
    },
    handelMoveItem(e) {
      this.flag = e.scroll;
    },
    // 检测抽签购可参与地区
    async checkDrawDistrict(id, type) {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      const json = await api.checkDrawDistrict({
        method: "POST",
        header: {
          jwt: customerInfo.jwt,
        },
        query: {
          activitySelectionId: this.activitySelectionId,
          customerAddressId: id,
        },
      });
      if (json.code == 1000) {
        if (type == "add") {
          this.$refs.addressAdd.openDialog();
        } else if (type == "list") {
          this.$refs.addressList.openDialog();
        }
      } else {
        if (type == "add") {
          this.$refs.addressAdd.openDistrictDialog(id);
        } else if (type == "list") {
          this.$refs.addressList.openDistrictDialog();
        }
      }
    },
    //登记
    async checkIn(addressId, type) {
      let that = this;
      if (this.secondRequest) {
        that.$commonSensors.popupEvent("PopupExposure", {
          popup_type: "订阅消息",
          popup_name: "订阅消息弹窗",
        });
        that.$commonSensors.modelAuthAsk("活动", [
          "u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc",
        ]);
        uni.requestSubscribeMessage({
          tmplIds: ["u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc"],
          success(res) {
            if (res.u8hwBNiXZpt6IHeLjh1RlrmTjuScvjXXMG_un2RgOSc == "accept") {
              that.resultDrawMessage(addressId, type);
              that.$commonSensors.popupEvent("PopupClick", {
                popup_type: "订阅消息",
                popup_name: "订阅消息弹窗",
                button_name: "允许",
              });
            } else {
              that.checkTrue(addressId, type);
              that.$commonSensors.popupEvent("PopupClick", {
                popup_type: "订阅消息",
                popup_name: "订阅消息弹窗",
                button_name: "拒绝",
              });
            }
          },
          fail(res) {
            that.checkTrue(addressId, type);
          },
          complete(res) {},
        });
      } else {
        that.checkTrue(addressId, type);
      }
    },
    async checkTrue(addressId, type) {
      this.fromSuccess = false;
      let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO) || "";
      let json = await api.drawItNow({
        method: "POST",
        header: {
          jwt: jwt,
        },
        query: {
          skuId: this.skuId,
          storeId: merchantInfo.cloudMerchantStoreId,
          activitySelectionId: this.activitySelectionId,
          addressId: addressId || uni.getStorageSync("addressId"),
          captchaTicket: this.params.captchaTicket,
        },
      });
      if (json.code == 1000) {
        //抽签购-确认登记埋点
        this.drawTrack("c_ebmp_draws_confirmaddress", {});
        this.$commonSensors.popupEvent("PopupClick", {
          popup_type: "购买",
          popup_name: "确认登记信息弹窗",
          button_name: "确认登记",
        });
        this.skipSuccess();
        this.fromSuccess = true;
        this.$commonSensors.drawSuccessTrack(
          "ParticipationDrawlots",
          this.params
        );
      } else {
				this.handleShowTextToast(json.msg || "登记已过期");
        // uni.showToast({
        //   title: json.msg || "登记已过期",
        //   icon: "none",
        //   mask: true,
        //   duration: 1500,
        // });
        if (type == "add") {
          this.$refs.addressAdd.delUserAddress(addressId);
        }
      }
    },
    async isSecondResultRquest() {
      let that = this;
      const accountInfo = uni.getAccountInfoSync();
      let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
      let customerInfo =
        uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
      let res = await api.getSaleMessage({
        method: "POST",
        header: {
          jwt: customerInfo ? customerInfo.jwt : "",
        },
        query: {
          name: "甄选佳酿活动结果通知",
          appId: accountInfo.miniProgram.appId,
          openId: userSpecialInfo.openid,
          params: {
            itemName: this.params.itemName,
            publicationTime: this.params.publicationTime,
            activityId: this.params.activitySelectionId,
            activityName: this.params.activityName,
          },
        },
      });
      if (res.code !== 1000) {
        this.secondRequest = true;
      } else {
        this.secondRequest = false;
      }
    },
    async resultDrawMessage(addressId, type) {
      let that = this;
      let userSpecialInfo = uni.getStorageSync(USER_SPECICAL_INFO);
      const accountInfo = uni.getAccountInfoSync();
      let customerInfo =
        uni.getStorageSync(CUSTOMER_INFO) || getApp().globalData.customerInfo;
      let page = `/pages/item/item?id=${this.params.goodsId}&valueId=${this.params.valueId}&valueName=${this.params.colorName}`;
      if (customerInfo) {
        let res = await api.sendSubMessage({
          method: "POST",
          header: {
            jwt: customerInfo.jwt,
          },
          query: {
            name: "甄选佳酿活动结果通知",
            appId: accountInfo.miniProgram.appId,
            openId: userSpecialInfo.openid,
            params: {
              itemName: this.params.itemName,
              publicationTime: this.params.publicationTime,
              page: page,
              miniprogramState: this.eve,
              activityId: this.params.activitySelectionId,
              activityName: this.params.activityName,
            },
          },
        });
        if (res.code == 1000) {
          // uni.showToast({
          //   title: "订阅成功",
          //   icon: "success",
          //   mask: true,
          //   duration: 1500,
          // });
					that.handleShowTextToast("订阅成功");
          setTimeout(function () {
            that.checkTrue(addressId, type);
          }, 1500);
        } else {
          that.checkTrue(addressId, type);
        }
      }
    },
    skipSuccess() {
      //抽签购登记成功埋点
      this.drawTrack("c_ebmp_draws_registered", {});
      // uni.navigateTo({
      //   url: '/pages/draw/checkSuccess?option=' + encodeURIComponent(JSON.stringify(this.params))
      // })
      uni.navigateBack();
    },
    drawTrack(eventName, params) {
      let clTrackPram = {
        c_draw_campaign_id: this.params.activitySelectionId,
        c_draw_campaign_name: this.params.activityName,
        c_campaign_time_register: this.params.drawStartTrackTime,
        c_campaign_time_announce: this.params.promulgateTrackTime,
        c_campaign_time_end: this.params.activityEndTrackTime,
        c_product_name: this.params.itemName,
        c_product_brand: this.params.brand,
        c_product_price: this.params.price,
        c_product_series: this.params.series,
        c_product_alcoholconcentration: this.params.degrees,
        c_product_volume: this.params.colorName,
        c_product_id: this.params.itemId,
        c_level_when_join: this.params.levelname,
        c_group_id: this.params.remark,
        c_skuid: this.params.skuId,
        c_campaign_time_register_end: this.params.exEndTrackTime,
        c_campaign_time_announce_end: this.params.buyEndTrackTime,
      };
      let clTrackPrams = Object.assign(clTrackPram, params);
      getApp().commonClTrack(eventName, clTrackPrams);
    },
	getOrderInfo: async function() {
	  let that = this;
	  let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
	  const json = await api.getOrderInfoWithTime({
	      header: {
	        jwt: customerInfo.jwt
	      }
	    },
	    this.no
	  );
	  if (json.data.code === 1000) {
		  let obj = json.data.data
		 return (obj.status == 'WAIT_SELLER_SEND_GOODS') || (obj.status == 'WAIT_BUYER_PAY'||obj.status == 'BUYER_PART_PAYMENT')
	    
		}else {
			return false
		}
	},	
    async applyGift(address) {
      const params = {
        gift_name: this.giftInfoOpt.giftName ||'',
        is_success: false,
        failure_reason: "",
      };
      try {
        this.fromSuccess = false;
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        const json = await api.applyGift({
          method: "POST",
          header: {
            jwt: jwt,
          },
          query: {
            id: this.giftInfoOpt.id,
            receiverAddress: address.receiverAddress,
            receiverCity: address.receiverCity,
            receiverDistrict: address.receiverDistrict,
            receiverMobile: address.receiverMobile,
            receiverName: address.receiverName,
            receiverState: address.receiverState,
            receiverTown: address.receiverTown,
            receiverZip: address.zipCode,
          },
        });
        if (json.code === 1000 && json.data && json.data.recordId) {
          params.is_success = true;
          this.fromSuccess = true;
          // uni.navigateTo({
          //   url: '/pages/memberGift/applySuccess?recordId=' + json.data.recordId
          // })

          uni.redirectTo({
            url: `/pages/memberGift/giftDetail?id=${this.giftInfoOpt.id}&isGetGiftTrue=true`,
          });
        } else {
          params.is_success = false;
          params.failure_reason = json.msg;
          this.handleShowTextToast(json.msg);
        }
      } catch (e) {
        params.is_success = false;
        params.failure_reason = e;
      }
      this.$commonSensors.paramsTrack("GiftsGet", params);
    },

    reSetAddModel(cb) {
      this.isTip = "tip";
      this.tipBgImg ="https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/addressaddress/ContentTip2.png";
      this.cb = cb;
      // this.reSetAddModelPass()
    },
    reSetAddModelCancel() {
      this.cb = null;
      this.isTip = null;
      this.tipBgImg = null;
	  this.reSeting = false
    },
    async reSetAddModelPass() {
		if(this.reSeting) return;
		this.reSeting = true
		 uni.showLoading();
		let isTrue = await this.getOrderInfo() 
		if(isTrue) {
			this.cb();
			// this.reSetAddModelCancel();
		} else {
		  uni.hideLoading();		
		  this.reSeting = false	
		  this.isTip = "fail";
		  this.tipBgImg ="https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/addressaddress/ContentTip1.png";
		}
    
    },
    reSetAddressId: async function (id, type) {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      let jwt = customerInfo.jwt;
      let pages = getCurrentPages();
      let cartKey = uni.getStorageSync("cartKey");

      // 获取顾客地址信息
      const json = await api.upOrderAddress(
        {
          method: "PUT",
          header: {
            jwt: jwt,
          },
          query: { customerAddressId: id },
        },
        this.orderNo
      );
      uni.hideLoading();
      if (json.code === 1000) {
				this.isTip = null;
				this.handleShowTextToast("收货地址已修改成功");
        setTimeout(() => {
          uni.navigateBack();
        }, 3000);
      } else {
        this.isTip = "fail";
        this.tipBgImg ="https://100000063-1252208446.file.myqcloud.com/images/MF-EB-P4/addressaddress/ContentTip1.png";
      }
			this.reSeting = false;
    },
  },
};
</script>
<style lang="less">
.hidden {
  display: none;
}

.icon-document-edit1 {
  font-size: 44rpx;
  margin: 63rpx 38rpx;
  display: block;
}

.mask-box-2 {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
  background-color: rgba(0, 0, 0, 0.8);
}

.params-padding-box-3 {
  overflow: hidden;
  background: #ffffff;
  position: absolute;
  left: 48rpx;
  width: 654rpx;
  // height: 744rpx;
}
</style>